<template>
  <div
    class="login"
    :style="{
      background: 'url(' + coverImgUrl + ')  no-repeat 50%',
    }"
  >
    <div class="login-box">
      <h1>mall-admin系统</h1>
      <div class="login-form">
        <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm">
          <div class="login-input">
            <el-form-item prop="username">
              <el-input
                placeholder="账号"
                v-model="ruleForm.username"
                clearable
              />
            </el-form-item>
          </div>
          <div class="login-input">
            <el-form-item prop="password">
              <el-input
                placeholder="密码"
                @keyup.enter="handleLogin(ruleFormRef)"
                v-model="ruleForm.password"
                show-password
                type="password"
              />
            </el-form-item>
          </div>

          <div class="login-btn">
            <el-button
              type="primary"
              @click="handleLogin(ruleFormRef)"
              :loading="loading"
              >登录</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { useStore } from "vuex";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import type { ElForm } from "element-plus";
import { login, queryUserPermissions } from "@/api/user";
import { ObjTy } from "@/types/common";
import { AccountLoginParams } from "./types/index";
import { generateRoute } from "@/utils/utils";
import { queryValueByKey } from "@/api/config";

const store = useStore();

type FormInstance = InstanceType<typeof ElForm>;

const ruleFormRef = ref<FormInstance>();

const router = useRouter();

const loading = ref<boolean>(false);

const coverImgUrl = ref("");
const baseImg = "../../src/assets/image/loginBj.png";

interface User {
  username: string;
  password: string | number;
}

const ruleForm = reactive<AccountLoginParams>({
  username: "",
  password: "",
});

const rules = reactive({
  username: [
    {
      required: true,
      message: "请输入账号",
      trigger: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "请输入密码",
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  getBgImg();
});

const getBgImg = async () => {
  let res = await queryValueByKey({ params_key: "loginBgImg" });
  console.log("登录背景:", res);
  if (res && res.data.params_value) {
    coverImgUrl.value = res.data.params_value;
  } else {
    coverImgUrl.value = baseImg;
  }
};

const loadRoutes = async () => {
  const token = localStorage.getItem("accessToken");
  if (token) {
    try {
      const { data } = await queryUserPermissions({});
      let routes = generateRoute(data);
      routes.map((route: any) => {
        let _component = route.component;
        route.component = () =>
          import(`./../../../src/views/${_component}/index.vue`);
        router.addRoute("main", route);
      });
    } catch (error) {}
  }
};

const handleLogin = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      const { username, password } = ruleForm;
      const params: ObjTy = {
        username,
        password,
      };
      login(params).then(async (res: ObjTy) => {
        try {
          if (res.code === 200) {
            ElMessage({
              message: "登录成功",
              type: "success",
            });
            // 临时加token 后续优化更改
            localStorage.setItem("accessToken", res.data.token);
            await loadRoutes();
            loading.value = false;
            router.push("/");
            store.commit("login", {
              userInfo: { name: "测试临时加" },
              token: res.data.token,
            });
            console.log("res.data.token", res.data.token);
            return;
          }
          loading.value = false;
        } catch (error) {
          console.log(error);
          loading.value = false;
        }
      });
    } else {
      console.log("error submit!");
      return false;
    }
  });
};
</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100vh;
  // background: url(../../assets/image/loginBj.png) no-repeat 50%;
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;

  .login-box {
    h1 {
      text-align: center;
      color: #fff;
      font-size: 34px;
    }
    .login-form {
      padding: 70px 50px;
      border-radius: 6px;
      background: #fff;
      width: 400px;
      .login-btn {
        button {
          width: 100%;
        }
      }
    }
  }
}
</style>
